"""
MAESS系统配置管理
包含所有系统配置参数，支持环境变量覆盖
"""

import os
from typing import List, Optional
from dataclasses import dataclass, field
from enum import Enum


class Environment(Enum):
    """环境枚举"""
    DEVELOPMENT = "development"
    TESTING = "testing"
    STAGING = "staging"
    PRODUCTION = "production"


@dataclass
class PerformanceDashboardConfig:
    """性能监控仪表板配置"""
    enabled: bool = True
    host: str = "0.0.0.0"
    port: int = 8080
    metrics_retention_hours: int = 24
    metrics_collection_interval: int = 5  # 秒
    max_metrics_per_type: int = 10000
    cors_origins: List[str] = field(default_factory=lambda: ["*"])
    
    # 智能体指标配置
    agent_metrics_enabled: bool = True
    agent_heartbeat_interval: int = 30  # 秒
    agent_timeout_threshold: int = 120  # 秒
    
    # 告警配置
    alerting_enabled: bool = True
    cpu_threshold: float = 80.0  # CPU使用率告警阈值
    memory_threshold: float = 85.0  # 内存使用率告警阈值
    error_rate_threshold: float = 5.0  # 错误率告警阈值
    response_time_threshold: int = 2000  # 响应时间告警阈值（毫秒）


@dataclass
class DatabaseConfig:
    """数据库配置"""
    host: str = "192.168.64.100"
    port: int = 5432
    database: str = "maess_db"
    username: str = "maess_user"
    password: str = "maess_password"
    pool_size: int = 20
    max_overflow: int = 30
    pool_timeout: int = 30
    pool_recycle: int = 3600


@dataclass
class RedisConfig:
    """Redis配置"""
    host: str = "localhost"
    port: int = 6379
    database: int = 0
    password: Optional[str] = None
    max_connections: int = 100
    socket_timeout: int = 5
    socket_connect_timeout: int = 5
    health_check_interval: int = 30


@dataclass
class RabbitMQConfig:
    """RabbitMQ配置"""
    host: str = "localhost"
    port: int = 5672
    virtual_host: str = "maess_vhost"
    username: str = "maess_user"
    password: str = "maess_password"
    heartbeat: int = 60
    connection_attempts: int = 3
    retry_delay: int = 5


@dataclass
class SecurityConfig:
    """安全配置"""
    jwt_secret_key: str = "your-secret-key-change-in-production"
    jwt_algorithm: str = "HS256"
    jwt_expiration_hours: int = 24
    api_key_header: str = "X-API-Key"
    rate_limit: str = "100/minute"
    cors_origins: List[str] = field(default_factory=lambda: ["*"])
    enable_swagger: bool = True


@dataclass
class LoggingConfig:
    """日志配置"""
    level: str = "INFO"
    format: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    file_enabled: bool = True
    file_path: str = "logs/maess.log"
    max_file_size: int = 100 * 1024 * 1024  # 100MB
    backup_count: int = 5
    console_enabled: bool = True


@dataclass
class MaessConfig:
    """MAESS系统主配置"""
    # 基础配置
    environment: Environment = Environment.DEVELOPMENT
    app_name: str = "MAESS智能体系统"
    app_version: str = "1.0.0"
    debug: bool = False
    
    # 服务器配置
    host: str = "0.0.0.0"
    port: int = 8000
    workers: int = 1
    
    # 子配置
    database: DatabaseConfig = field(default_factory=DatabaseConfig)
    redis: RedisConfig = field(default_factory=RedisConfig)
    rabbitmq: RabbitMQConfig = field(default_factory=RabbitMQConfig)
    security: SecurityConfig = field(default_factory=SecurityConfig)
    logging: LoggingConfig = field(default_factory=LoggingConfig)
    performance_dashboard: PerformanceDashboardConfig = field(default_factory=PerformanceDashboardConfig)
    
    # API配置
    api_prefix: str = "/api"
    api_timeout: int = 30
    
    # 智能体配置
    agent_timeout: int = 300  # 智能体超时时间（秒）
    agent_max_retries: int = 3
    agent_retry_delay: int = 1
    
    # 监控配置
    enable_monitoring: bool = True
    metrics_endpoint: str = "/metrics"
    health_check_endpoint: str = "/health"


def load_config_from_env() -> MaessConfig:
    """从环境变量加载配置"""
    config = MaessConfig()
    
    # 基础配置
    config.environment = Environment(os.getenv("APP_ENV", "development"))
    config.debug = os.getenv("APP_DEBUG", "false").lower() == "true"
    config.app_name = os.getenv("APP_NAME", "MAESS智能体系统")
    config.app_version = os.getenv("APP_VERSION", "1.0.0")
    
    # 服务器配置
    config.host = os.getenv("APP_HOST", "0.0.0.0")
    config.port = int(os.getenv("APP_PORT", "8000"))
    config.workers = int(os.getenv("APP_WORKERS", "1"))
    
    # 数据库配置
    config.database.host = os.getenv("DB_HOST", "localhost")
    config.database.port = int(os.getenv("DB_PORT", "5432"))
    config.database.database = os.getenv("DB_NAME", "maess_db")
    config.database.username = os.getenv("DB_USER", "maess_user")
    config.database.password = os.getenv("DB_PASSWORD", "maess_password")
    
    # Redis配置
    config.redis.host = os.getenv("REDIS_HOST", "localhost")
    config.redis.port = int(os.getenv("REDIS_PORT", "6379"))
    config.redis.database = int(os.getenv("REDIS_DB", "0"))
    config.redis.password = os.getenv("REDIS_PASSWORD")
    
    # RabbitMQ配置
    config.rabbitmq.host = os.getenv("RABBITMQ_HOST", "localhost")
    config.rabbitmq.port = int(os.getenv("RABBITMQ_PORT", "5672"))
    config.rabbitmq.virtual_host = os.getenv("RABBITMQ_VHOST", "maess_vhost")
    config.rabbitmq.username = os.getenv("RABBITMQ_USER", "maess_user")
    config.rabbitmq.password = os.getenv("RABBITMQ_PASSWORD", "maess_password")
    
    # 安全配置
    config.security.jwt_secret_key = os.getenv("JWT_SECRET_KEY", "your-secret-key-change-in-production")
    config.security.api_key_header = os.getenv("API_KEY_HEADER", "X-API-Key")
    config.security.rate_limit = os.getenv("RATE_LIMIT", "100/minute")
    
    # 性能监控仪表板配置
    config.performance_dashboard.enabled = os.getenv("DASHBOARD_ENABLED", "true").lower() == "true"
    config.performance_dashboard.host = os.getenv("DASHBOARD_HOST", "0.0.0.0")
    config.performance_dashboard.port = int(os.getenv("DASHBOARD_PORT", "8080"))
    config.performance_dashboard.metrics_retention_hours = int(os.getenv("METRICS_RETENTION_HOURS", "24"))
    config.performance_dashboard.metrics_collection_interval = int(os.getenv("METRICS_COLLECTION_INTERVAL", "5"))
    
    return config


# 全局配置实例
settings = load_config_from_env()


def get_settings() -> MaessConfig:
    """获取系统配置"""
    return settings


def reload_settings() -> MaessConfig:
    """重新加载配置"""
    global settings
    settings = load_config_from_env()
    return settings